package com.android.qjpmc.application_module.activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PointF;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.contract.StationContract;
import com.android.qjpmc.application_module.station.fragment.PwrDiagramFragment;
import com.android.qjpmc.application_module.station.fragment.ReportDataFragment;
import com.android.qjpmc.application_module.station.fragment.RtCurveFragment;
import com.android.qjpmc.application_module.station.fragment.RtDataFragment;
import com.android.qjpmc.application_module.station.fragment.StationVideoFragment;
import com.android.qjpmc.application_module.viewModel.StationViewModel;
import com.android.qjpmc.bean.StationDataBean;
import com.android.qjpmc.bean.TabListBean;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.data_module.PwrStation;
import com.android.qjpmc.databinding.ActivityStationBinding;
import com.android.qjpmc.kernel.JxtXmlPara;
import com.android.qjpmc.kernel.MyReceiver;
import com.android.qjpmc.manager.FragmentManager;
import com.android.qjpmc.widget.base.BaseFragmentAdapter;
import com.android.qjpmc.widget.base.BasePageManageActivity;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.utils.UIUtils;
import com.android.qjpmc.widget.view.tablayout.TabLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

@CreateViewModel(StationViewModel.class)
//变电站
public class StationActivity extends BasePageManageActivity<StationViewModel, ActivityStationBinding> implements StationContract.View {

    private List<TabListBean> tabList;
    private List<Fragment> fragmentList;
    private List<String> titleList;
    private BaseFragmentAdapter adapter;

    PwrStation ThePwrStation = null;

    //接线图Fragment
    private PwrDiagramFragment jxtFragment = null;
    //选择数据Fragment
    private Fragment selectdataFragment = null;
    //实时数据Fragment
    private RtDataFragment realdataFragment = null;
    //参数Fragment
    private Fragment paraFragment = null;
    //报表Fragment
    private ReportDataFragment hisdataFragment = null;

    //曲线Fragment
    private RtCurveFragment CurveFragment = null;

    //视频Fragment
    private StationVideoFragment StationVideoFragment = null;

    StationActivity DataShowActivity = null;

    public int m_UserID;
    public int Sign = 0;
    public int Sign1 = 0;

    int StationNum = 0;
    String StationName[] = new String[10];
    int StationIDEx[] = new int[10];

    public int StationID = 0;
    public int StationIndex;
    public int GroupID;
    public int GroupType;
    public int DataNum;
    public int Port1;
    public int Port2;
    public String GroupName = null;
    // 底部菜单4个Linearlayout
    private LinearLayout ll_jxt;
    private LinearLayout ll_realdata;
    private LinearLayout ll_para;
    private LinearLayout ll_hisdata;

    // 底部菜单4个ImageView
    private ImageView iv_jxt;
    private ImageView iv_realdata;
    private ImageView iv_para;
    private ImageView iv_hisdata;
    // 底部菜单4个菜单标题
    private TextView tv_jxt;
    private TextView tv_realdata;
    private TextView tv_para;
    private TextView tv_hisdata;

    public TextView tv_top_title;

    // 4个Fragment

    //用户数据----------------------------------------------------------------------------
    int AddSign[] = new int[5];

    private int CurID = -1;
    int ThreadSign = 0;
    NotificationManager mNotificationManager;
    NotificationCompat.Builder mBuilder;
    int notifyId = 1;

    private MyReceiver MyRecv;
    private IntentFilter intentFilter;

    JxtXmlPara m_Jxt = null;
    public int m_JxtSign = -1;

    String m_BasePath = "";
    int m_DownJxtSign = 0;

    private GestureDetector gestureDetector;

    final public static int DRAG = 1;
    final public static int ZOOM = 2;

    public int mode = 0;


    private float x_down = 0;
    private float y_down = 0;

    private PointF mid = new PointF();


    private float initDis = 1f;

    public int screenWidth, screenHeight;

    private float[] x = new float[4];
    private float[] y = new float[4];

    private boolean flag = false;
    private String stationId;
    private String companyName;
    //-----------------------------------------------------------------------------------

    @Override
    public int getLayoutId() {
        return R.layout.activity_station;
    }

    @Override
    public void initView() {
        super.initView();
        stationId = getIntent().getStringExtra("stationId");
        mBinding.setView(this);
        ThePwrStation = PwrDataModule.getInstance().GetCurrentStationNode();
        companyName = ThePwrStation.getM_Name();
        if (ThePwrStation != null) {
            mBinding.toolbar.setTitleText(companyName + "监视");// getToolsBar().setTitle("HLLL");
        } else {
            mBinding.toolbar.setTitleText("未知站点");
        }
        tabList = new ArrayList<TabListBean>();
        tabList.add(new TabListBean(1, "监控画面"));
        tabList.add(new TabListBean(2, "实时数据"));
        tabList.add(new TabListBean(3, "实时曲线"));
        tabList.add(new TabListBean(4, "视频监视"));
        fragmentList = new ArrayList<>();
        titleList = new ArrayList<>();

    }

    @Override
    public void initData() {
        super.initData();
        //todo 胖胖修改: 先从服务器获取
        //不从服务器取参数
        requestNetData();
        //直接从数据池里面获取
       /* if (ThePwrStation != null) {
            showContent(ThePwrStation.GetDeviceListCntnBean());
        }*/
    }

    @Override
    protected void requestNetData() {
        mViewModel.getGroupListOfStation(stationId);
    }

    @Override
    protected View getPageManagerView() {
        return mBinding.llContent;
    }

    @Override
    public void initEvent() {
        super.initEvent();
        mBinding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mBinding.tabLayout.getTabAt(position).select();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateTabTextView(tab, true);
                if (adapter != null && adapter.getCount() > 0 && mBinding.tabLayout.getTabCount() > 0)
                    mBinding.viewPager.setCurrentItem(tab.getPosition());

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabTextView(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

    }

    public void updateTabTextView(TabLayout.Tab tabSelect, boolean isSelect) {
        View bgView = tabSelect.getCustomView().findViewById(R.id.view_bg);
        TextView tvTitle = tabSelect.getCustomView().findViewById(R.id.tv_title);
        tvTitle.setTextColor(UIUtils.getColor(isSelect ? R.color.color_fefefe : R.color.gray_66));
        bgView.setBackgroundResource(isSelect ? R.drawable.shape_color_244395_18dp : R.drawable.shape_color_f0f0f0_15dp);
    }

    private View getTabView(final TabListBean tabListBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_station, null);
        TextView textView = view.findViewById(R.id.tv_title);
        textView.setText(tabListBean.title);
        return view;
    }

    /*
        @Override
        public void onCreate(Bundle savedInstanceState) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_station);
         //   StatusBarUtils.setStatusBarMode(this, true, R.color.white);

            gestureDetector = new GestureDetector(StationActivity.this,onGestureListener);

            Bundle bundle = this.getIntent().getExtras();
            m_UserID = bundle.getInt("UserID");

            for(int i=0;i<5;i++) AddSign[i]=0;
            // 初始化控件
            initView();
            // 初始化底部按钮事件

            ShowFragment(1);

            initEvent();
            // 初始化并设置当前Fragment
            InitNotiy();

        //    selectdataFragment.setOnButtonClick(new SelectFragment.OnButtonClick() {

         //       @Override
        //        public void onClick(View view) {
                    //切换到TwoFragment
         //           ShowFragment(4);
         //           if (Sign == 1)
         //               realdataFragment.InitList();
          //          Sign = 1;
         //       }
        //    });





            m_Jxt=new JxtXmlPara();
            String Path1 = "Chart";
            String Path2 = "User_" + Integer.toString(m_UserID);
            String fileName = "Chart.xml";
            m_BasePath = this.getApplicationContext().getFilesDir() + "";
            m_Jxt.m_ChartPath = m_BasePath + "/" + Path1 + "/" + Path2 + "/" + fileName; //文件存储路径

            //m_JxtSign = m_Jxt.ReadJxtXml();
            if (m_JxtSign == 0) {
            }
            else
            {
                DownLoadJxt();
            }

            // ATTENTION: This was auto-generated to implement the App Indexing API.
            // See https://g.co/AppIndexing/AndroidStudio for more information.
          //  client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        }
    */
    private GestureDetector.OnGestureListener onGestureListener =
            new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                       float velocityY) {
                    float x = e2.getX() - e1.getX();
                    float y = e2.getY() - e1.getY();

                    if (CurID == 0 && m_Jxt.m_Qjpmc_XmlCnfg.m_PageNum > 1) {

                        /*
                        if (x > 0) {
                            jxtFragment.m_JxtPos--;
                            if(jxtFragment.m_JxtPos<0) jxtFragment.m_JxtPos=m_Jxt.m_XmlCnfg.m_PageNum-1;
                            jxtFragment.m_JxtView.invalidate();
                        } else if (x < 0) {
                            jxtFragment.m_JxtPos++;
                            if(jxtFragment.m_JxtPos>=m_Jxt.m_XmlCnfg.m_PageNum) jxtFragment.m_JxtPos=0;
                            jxtFragment.m_JxtView.invalidate();
                        }
                        */

                    }
                    return true;
                }
            };


    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        // 多点触摸的时候 必须加上MotionEvent.ACTION_MASK
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                x_down = event.getX();
                y_down = event.getY();
                // 初始为drag模式
                mode = DRAG;
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                // 初始的两个触摸点间的距离
                initDis = spacing(event);
                // 设置为缩放模式
                mode = ZOOM;
                // 多点触摸的时候 计算出中间点的坐标
                midPoint(mid, event);
                break;

            case MotionEvent.ACTION_MOVE:
                // drag模式
                if (mode == DRAG && jxtFragment.m_JxtView.m_FShowRate > 1) {//
                    // 平移 当前坐标减去初始坐标 移动的距离
                    float x = jxtFragment.m_JxtView.m_CenterPnt.x - (event.getX() - x_down);
                    float y = jxtFragment.m_JxtView.m_CenterPnt.y - (event.getY() - y_down);
                    x_down = event.getX();
                    y_down = event.getY();

                    flag = true;
                    if (x >= screenWidth) flag = false;
                    if (x <= 0) flag = false;
                    if (y >= screenHeight) flag = false;
                    if (y <= 0) flag = false;
                    // 判断达到移动标准
                    if (flag) {
                        // 设置matrix
                        jxtFragment.m_JxtView.m_CenterPnt.x = x;
                        jxtFragment.m_JxtView.m_CenterPnt.y = y;
                        jxtFragment.m_JxtView.SetShowType();

                    }
                } else if (mode == ZOOM) {
                    float newDis = spacing(event);
                    // 计算出缩放比例
                    float scale = newDis / initDis;

                    if (scale > 1) scale = 1 + (scale - 1) / 2;

                    float ShowRate = jxtFragment.m_JxtView.m_FShowRate * scale;

                    if (ShowRate > 3) ShowRate = 3;
                    else if (ShowRate < 1) ShowRate = 1;
                    // 以mid为中心进行缩放
                    if (jxtFragment.m_JxtView.m_FShowRate == ShowRate) break;
                    jxtFragment.m_JxtView.m_CenterPnt.x = mid.x;
                    jxtFragment.m_JxtView.m_CenterPnt.y = mid.y;
                    jxtFragment.m_JxtView.m_FShowRate = ShowRate;
                    jxtFragment.m_JxtView.SetShowType();
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = 0;
                break;
        }
        if (jxtFragment.m_JxtView.m_FShowRate == 1 && mode != ZOOM)
            return gestureDetector.onTouchEvent(event);
        else
            return super.onTouchEvent(event);
    }

    //取两点的距离
    private float spacing(MotionEvent event) {
        try {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return (float) Math.sqrt(x * x + y * y);
        } catch (IllegalArgumentException ex) {
            Log.v("TAG", ex.getLocalizedMessage());
            return 0;
        }
    }

    //取两点的中点
    private void midPoint(PointF point, MotionEvent event) {
        try {
            float x = event.getX(0) + event.getX(1);
            float y = event.getY(0) + event.getY(1);
            point.set(x / 2, y / 2);
        } catch (IllegalArgumentException ex) {

            //这个异常是android自带的，网上清一色的这么说。。。。
            Log.v("TAG", ex.getLocalizedMessage());
        }
    }

    public int DownLoadJxt() {
        String urlStr = "http://39.108.172.55/Chart/User_" +
                Integer.toString(m_UserID) + "/Chart.xml";
        String Path1 = "Chart";
        String Path2 = "User_" + Integer.toString(m_UserID);
        String fileName = "Chart.xml";

        String pathName = m_BasePath + "/" + Path1 + "/" + Path2 + "/";//文件存储路径

        try {
            File filePath = new File(pathName);
            if (!filePath.exists()) {
                if (filePath.mkdirs()) {
                } else {
                    return 0;

                }
            }

            pathName = m_BasePath + "/" + Path1 + "/" + Path2 + "/" + fileName;
            File file = new File(pathName);
            if (file.exists()) {
                file.delete();
            }

            // 构造URL
            URL url = new URL(urlStr);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(pathName);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        m_DownJxtSign = 1;
        m_JxtSign = m_Jxt.ReadJxtXml();

        if (m_JxtSign == 0) {
            ShowFragment(0);
            restartBotton();
            tv_jxt.setTextColor(0xff333333);
        }
        return 0;
    }


    public PendingIntent getDefalutIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }

    public void ShowFragment(int index) {
        ;
    }

    public void InitNotiy() {
/*
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this.getApplicationContext());


        MyRecv = new MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("notification_clicked");
        this.getApplicationContext().registerReceiver(MyRecv, intentFilter);

        MyRecv.SetJumpToEvent(new JumpToEvent() {
            @Override
            public void ShowEvent() {

                mNotificationManager.cancel(notifyId);
                restartBotton();

                tv_hisdata.setTextColor(0xff333333);
                tv_top_title.setText("历史数据");

                if (layout != null)
                    layout.setVisibility(View.GONE);
                if (layout1 != null)
                    layout1.setVisibility(View.GONE);
                ShowFragment(3);
            }
        });

        Intent intentClick = new Intent();//(this.getApplicationContext(),MyRecv.getClass());
        intentClick.setAction("notification_clicked");
        intentClick.putExtra(MyRecv.TYPE, notifyId);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intentClick, PendingIntent.FLAG_UPDATE_CURRENT);


        mBuilder.setContentTitle("提醒")//设置通知栏标题
                .setContentText("电站有新的告警事件！") // /<span style="font-family: Arial;">/设置通知栏显示内容</span>
                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
                //	.setNumber(number) //设置通知集合的数量
                .setTicker("电站有新的告警事件！") //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                //	.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setContentIntent(pendingIntentClick)
                .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON

 */
    }

    private void restartBotton() {

    }


    @Override
    public void showError(String message, int code) {
        mPageManage.showError(message);

    }

    @Override
    public void showLoading(String message) {
        mPageManage.showLoading();
    }

    @Override
    public void showContent(StationDataBean data) {
        data.companyName= companyName;
        data.companyId= stationId;
        mPageManage.showContent();
        for (int i = 0; i < tabList.size(); i++) {
            TabListBean tabListBean = tabList.get(i);
            titleList.add(tabListBean.title);
            if (tabListBean.id == 1) {
                jxtFragment = (PwrDiagramFragment) FragmentManager.getPwrDiagramFragment(tabListBean.id);
                fragmentList.add(jxtFragment);
            } else if (tabListBean.id == 2) {
                realdataFragment = (RtDataFragment) FragmentManager.getRtDataFragment(tabListBean.id);
                realdataFragment.initStationData(stationId, data);
                fragmentList.add(realdataFragment);
            } else if (tabListBean.id == 3) {
                CurveFragment = (RtCurveFragment) FragmentManager.getRtCurveFragment(tabListBean.id);
                CurveFragment.initStationData(stationId, data);

                fragmentList.add(CurveFragment);
            } else if (tabListBean.id == 4) {
                StationVideoFragment = (StationVideoFragment) FragmentManager.getVideoFragment(tabListBean.id);
                StationVideoFragment.initStationData(stationId, data);
                fragmentList.add(StationVideoFragment);
            }
            final TabLayout.Tab tab = mBinding.tabLayout.newTab();
            tab.setCustomView(getTabView(tabListBean));
            final View tabView = (View) tab.getCustomView().getParent();
            tabView.setTag(i);
            mBinding.tabLayout.addTab(tab);
        }
        updateTabTextView(mBinding.tabLayout.getTabAt(0), true);
        adapter = new BaseFragmentAdapter(getSupportFragmentManager(), titleList, fragmentList, 1);
        mBinding.viewPager.setAdapter(adapter);
    }

    @Override
    public void showEmpty(String message) {
        mPageManage.showEmpty(message);

    }
}